<template>
  <div class="param_compare">
    <one-title title="工艺参数查询及对比" @refreshData="init">
      <div class="mes_btn">
        <el-button
          v-btn-permission="'compare'"
          @click="handleCompare"
          type="success">
          <i class="iconfont icon-btn_addnew"></i>
          生成数据
        </el-button>
      </div>
    </one-title>
    <div class="bom_tree_container">
      <work-order-bom-tree
        @selectNode="selectNode"
        class="mes_tree bom_tree"
      ></work-order-bom-tree>
      <div class="compare_choose">
        <CompareStageTable
          @change="handleStageChange"
          class="table_stage"
          ref="compareStageTable">
        </CompareStageTable>
        <CompareTempTable
          class="table_param"
          ref="compareTempTable">
        </CompareTempTable>
        <div class="mes_btn">
          <el-button @click="handleAdd" type="primary">
            添加到
            <i class="iconfont icon-arrow_lien_right"></i>
          </el-button>
        </div>
        <CompareTargetTable
          @delete="handleDelete"
          class="table_target"
          ref="compareTargetTable">
        </CompareTargetTable>
      </div>
    </div>
  </div>
</template>

<script>
import {CompareStageTable, CompareTargetTable, CompareTempTable} from './components'

// 根据工单id获取工序接口：/{id} get
let interfaceGetStage = 'a/workorder/workorder/getworkorder'

// 根据工单-工序的id获取模板: {"workstageId":"工单-工序的id","entry":"workorder"} post
let interfaceGetParamTemp = 'a/workstagerecordtemplate/workstageRecordTemplate/retrieveparamtemplate'

export default {
  name: 'ParamCompare',
  components: {
    CompareStageTable,
    CompareTempTable,
    CompareTargetTable
  },
  data() {
    return {
      workorderId: undefined,
      workorderNumber: '', //选中的工单编号
      materialName: '', //选中的工单物料名称
      workorder: {}, // 工单信息
      workstageId: '',
    }
  },
  methods: {
    /**
     * 选择树节点的到工单id
     * @param id 工单id
     * @param number 工单编号
     * @param level 节点级别
     * @param name  节点物料名称
     */
    selectNode(id, number, level, name) {
      this.workorderId = id
      this.workorderNumber = number
      this.materialName = name
      this.init()
    },
    async init() {
      if (this.workorderId === undefined) return
      this.$refs.compareTempTable.init()
      this.getStage().then(res => {
        this.$refs.compareStageTable.init(res.data.workorderWorkstageList)
        this.workorder = res.data.workorder
      })
    },
    handleStageChange(stage) {
      this.$refs.compareTempTable.init()
      this.workstageId = stage.id
      // 工序没有模板时不请求
      if (stage.paramTemplateId === undefined) return
      this.getTemp().then(res => {
        // 简化工序对象属性
        let stage = this.simpleStage(this.$refs.compareStageTable.currentRow)
        let tempItems = this.getTempJsonObj(res)
        // 以工单id+工序的id+模板项的name、type和标记列表项，并合并工序到模板项目
        let tempTableData = tempItems.reduce((pre, cur) =>
          [...pre, this.combineData(cur, stage, this.workorderId, this.workorderNumber, this.materialName)], [])
        // 以标记求交集将已添加过的模板项的isAdd属性置为true
        let targetTableData = this.$refs.compareTargetTable.tableData
        tempTableData = this.getIntersection(targetTableData, tempTableData)

        this.$refs.compareTempTable.init(tempTableData)
      })
    },
    /**
     * 以工单id+工序的id+模板项的name、type和标记列表项，并合并工序到模板项目
     * @param name 模板项名称
     * @param type 模板项类型
     * @param remarks 工序简述
     * @param stage 当前选中工序
     * @param workorderId 工单id
     * @param workorderNumber 工单编号
     * @param materialName 物料名称
     * @returns {*}
     */
    combineData({name, type, remarks}, stage, workorderId, workorderNumber, materialName) {
      return Object.assign({
        workorderId,
        workorderNumber,
        materialName,
        name,
        type,
        remarks,
        tag: workorderId + stage.id + name + type
      }, stage)
    },
    // todo 优化：判断inventory属性存在且为json字符串
    /**
     * @desc 转换模板json字符串为对象，并将工序简述添加到对象上
     * @param res
     * @returns {Array|*}
     */
    getTempJsonObj(res) {
      try {
        let inventory = JSON.parse(res.data.inventory)
        let remarks = res.data.remarks
        return inventory.reduce((pre, cur) => [...pre, {...cur, remarks}], [])
      } catch (e) {
        return []
      }
    },
    /**
     * 简化工序对象属性
     * @param id 工单工序id
     * @param sort 工序序号
     * @param workstageId 工序id
     * @param workstageName 工序名称
     * @returns {{id: *, workstageName: *, isAdd: boolean}}
     */
    simpleStage({id, sort, workstageId, workstageName, summary}) {
      return {id, sort, workstageId, workstageName, summary, isAdd: false}
    },
    /**
     * 以标记求交集将已添加过的模板项的isAdd属性置为true
     * @param arr1
     * @param arr2
     * @returns {*} 交集数组
     */
    getIntersection(arr1, arr2) {
      let tags1 = arr1.reduce((pre, cur) => [...pre, cur.tag], [])
      return arr2.reduce((pre, cur) => {
        cur.isAdd = tags1.includes(cur.tag)
        return [...pre, cur]
      }, [])
    },
    handleAdd() {
      let tempItems = this.$refs.compareTempTable.selectItems
      tempItems.map(v => {
        v.isAdd = true
      })
      this.$refs.compareTargetTable.handleAdd(tempItems)
      this.$refs.compareTempTable.clearSelection()
    },
    // 清空时重新初始化模板项表格
    handleDelete() {
      let tempTableData = this.$refs.compareTempTable.tableData
      let targetTableData = this.$refs.compareTargetTable.tableData
      tempTableData = this.getIntersection(targetTableData, tempTableData)
      this.$refs.compareTempTable.init(tempTableData)
    },
    handleCompare() {
      let prepareItems = this.$refs.compareTargetTable.tableData
      if (prepareItems.length === 0) {
        return this.$message.error({
          message: '请至少添加一条需要比较的数据',
          duration: 1500,
          center: true
        })
      }
      this.$store.commit('SetTargetTableData', prepareItems)
      this.$router.push('/paramCompareDetail')
    },
    // 根据工单id获取工序接口：/{id} get
    getStage() {
      let queryObj = {
        method: 'get',
        url: `${interfaceGetStage}/${this.workorderId}`,
        noCommit: true
      }
      this.$refs.compareStageTable.isLoading = true
      return this.$store.dispatch('saveData', queryObj).finally(() => {
        this.$refs.compareStageTable.isLoading = false
      })
    },
    // 根据工单-工序的id获取模板
    getTemp() {
      let queryObj = {
        method: 'post',
        url: `${interfaceGetParamTemp}`,
        data: {
          workstageId: this.workstageId,
          entry: 'workorder'
        },
        noCommit: true
      }
      this.$refs.compareTempTable.isLoading = true
      return this.$store.dispatch('saveData', queryObj).then(res => res).finally(() => {
        this.$refs.compareTempTable.isLoading = false
      })
    },
  }
}
</script>

<style lang="less" scoped>
  .param_compare {
    height: 100%;
    .compare_choose {
      box-sizing: border-box;
      padding: 20px;
      display: flex;
      .table_container {
        padding: 0;
      }
      .table_stage {
        width: 270px;
      }
      .table_param {
        padding: 0 20px;
        width: 300px;
      }
      .table_target {
        padding-left: 20px;
        flex: 1;
      }
    }
  }
</style>
